package logic

import (
	"context"
	"encoding/json"
	"strconv"
	"time"
	"ykone/models/mysql"
	"ykone/models/redis"

	"ykone/ykonerpc/internal/svc"
	"ykone/ykonerpc/ykonerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProduceListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProduceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProduceListLogic {
	return &ProduceListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProduceListLogic) ProduceList(in *ykonerpc.ProduceListRequest) (*ykonerpc.ProduceListResponse, error) {
	// todo: add your logic here and delete this line
	var produces []mysql.Produce
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	Itoa := strconv.Itoa(int(offset))
	get := redis.Client.Get("list" + Itoa)

	if get.Val() == "" {
		mysql.DB.Debug().Limit(int(in.Size)).Offset(int(offset)).Where("product_name like ?", "%"+in.ProductName+"%").Order("price desc").Find(&produces)
		marshal, _ := json.Marshal(&produces)
		redis.Client.Set("list"+Itoa, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &produces)
	}

	var ListStruct []*ykonerpc.ProductStruct
	for _, produce := range produces {
		list := ykonerpc.ProductStruct{
			ProductName:  produce.ProductName,
			ProductStore: produce.ProductStore,
			Price:        produce.Price,
			Img:          produce.Img,
			UserID:       int64(produce.UserId),
		}
		ListStruct = append(ListStruct, &list)
	}
	return &ykonerpc.ProduceListResponse{List: ListStruct}, nil
}
